package com.opd.soeghtool;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.NotificationCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsoluteLayout;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;

import com.nostra13.universalimageloader.BuildConfig;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class FloatMenuService extends Service {

    final String TAG = "SOEFMS";

    final int MENU_STAY_TIME = 15000;

    WindowManager windowManager;
    WindowManager.LayoutParams paramsFloat, paramsBtn, params, paramsDraw, paramsQuick, paramsPosition, paramsHide;
    LinearLayout layout_float_menu, ll_float_menu_quick, ll_float_menu_setting, ll_float_menu_home, ll_float_menu_visible, ll_float_menu_data, quickViewLayout;
    LinearLayout ll_position_data;
    AbsoluteLayout layout_btn_notouch, float_hide_layout;
    ConstraintLayout floatLogoLayout;
    ImageView iv_float_menu_visible, iv_float_menu_data, iv_float_menu_quick;
    TextView tv_float_menu_visible;
    Button btn_position_data_save, btn_position_data_load;
    GlobalVar mGlobalVar;
    int panelHeight, panelWidth;
    private int pttbl_temp[];
    private int combo_pttbl_temp[][];
    private int mImageHalfSize = 20, floatWindowSize = 100, mFloatHideSize = 5;
    ImageView iv_combo_btn[][];
    ImageView iv_normal_btn[];
    ListView lv_btnlist;
    FuncAdapter funcAdapter;
    ArrayList<Map<String, Object>> listData;

    boolean bIsMenuKeyShow = false, bIsImageAlreadyCreate = false;

    private int S2_X = 0, S2_Y = 0;
    private int g_prvOrientation = 0;

    boolean bIsLogoShow = false, bIsBtnNoTouchShow = false, bIsMenuShow = false, bIsHalfShow = false, bIsQuickShow = false, bIsPositionShow = false;

    private static Handler handler, handlerLandscape, handlerSystem;
    private Message message, message1, message2;
    MyBroadcastReceive myBroadcastReceive;

    byte u8DataBuffer[];
    byte g_u8tAttrTable[][];
    UdpSocketHelper udpSocketHelper;
    private LocationManager locationManager;


    @SuppressLint({"HandlerLeak", "ClickableViewAccessibility"})
    @Override
    public void onCreate() {
        super.onCreate();
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getRealMetrics(dm);
        mGlobalVar = (GlobalVar) getApplication();
        mGlobalVar.setIsFloatServiceRunning(true);
        paramsFloat = new WindowManager.LayoutParams();
        params = new WindowManager.LayoutParams();
        paramsDraw = new WindowManager.LayoutParams();
        paramsBtn = new WindowManager.LayoutParams();
        paramsQuick = new WindowManager.LayoutParams();
        paramsPosition = new WindowManager.LayoutParams();
        paramsHide = new WindowManager.LayoutParams();
        // windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        u8DataBuffer = new byte[Transfer_Con.HID_PACKET_SIZE];
        g_u8tAttrTable = new byte[mGlobalVar.getDeviceMaxButton()][3];
        udpSocketHelper = new UdpSocketHelper(4000, 4400);
        iv_normal_btn = new ImageView[Transfer_Con.APP_SUPPORT_MAX_BUTTON];
        iv_combo_btn = new ImageView[4][Transfer_Con.APP_SUPPORT_MAX_BUTTON - 2];


        paramsHide.format = paramsPosition.format = paramsQuick.format = paramsBtn.format = paramsDraw.format = paramsFloat.format = params.format = PixelFormat.RGBA_8888;
        //params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        //params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
        //params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
        paramsHide.flags = params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        paramsPosition.flags = paramsQuick.flags = paramsDraw.flags = paramsFloat.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//|WindowManager.LayoutParams.FLAG_FULLSCREEN;
        paramsBtn.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;//|WindowManager.LayoutParams.FLAG_FULLSCREEN;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            paramsHide.type = paramsPosition.type = paramsQuick.type = paramsBtn.type = paramsDraw.type = paramsFloat.type = params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            paramsHide.type = paramsPosition.type = paramsQuick.type = paramsBtn.type = paramsDraw.type = paramsFloat.type = params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            paramsHide.layoutInDisplayCutoutMode = paramsPosition.layoutInDisplayCutoutMode = params.layoutInDisplayCutoutMode = paramsQuick.layoutInDisplayCutoutMode = paramsBtn.layoutInDisplayCutoutMode = paramsDraw.layoutInDisplayCutoutMode = paramsFloat.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        //设置窗口初始停靠位置.
        paramsHide.gravity = paramsQuick.gravity = paramsBtn.gravity = paramsDraw.gravity = params.gravity = Gravity.START | Gravity.TOP;
        paramsFloat.gravity = Gravity.CENTER | Gravity.TOP;
        paramsPosition.gravity = Gravity.CENTER | Gravity.TOP;


        Log.d(TAG, String.format("wid=%d, hei=%d", dm.widthPixels, dm.heightPixels));
        panelHeight = dm.heightPixels;
        panelWidth = dm.widthPixels;

        if (panelWidth < panelHeight) {
            int a = panelWidth;
            panelWidth = panelHeight;
            panelHeight = a;
            Log.d(TAG, "swap to Landscape Mode");
        }
        //Toast.makeText(FloatMenuService.this,String.format("wid=%d, hei=%d---- %dX%d", dm.widthPixels, dm.heightPixels,mGlobalVar.getScreenHeight(),mGlobalVar.getScreenWidth()),Toast.LENGTH_LONG).show();
        if(Transfer_Con.ENABLE_DIFFERENT_RESOLUTION_GB) {

            mGlobalVar.tranSet_Value_retry(Transfer_Con.HID_CMD_SET_SCREEN_RESOLUTION, panelWidth, panelHeight, 3);
            /*
            if ((mGlobalVar.getScreenWidth() != panelHeight) && ((panelHeight == 1128) || (panelHeight == 752))) {
                panelHeight = mGlobalVar.getScreenWidth();
            }

            if ((mGlobalVar.getScreenHeight() != panelWidth) && ((panelWidth == 2400) || (panelWidth == 1600))) {
                panelWidth = mGlobalVar.getScreenHeight();
            }
            */
        }
        if (Transfer_Con.ENABLE_LANGUAGE_SWITCH) {
            Resources resources = getResources();
            Configuration config = resources.getConfiguration();
            //DisplayMetrics dm = resources.getDisplayMetrics();
            if (mGlobalVar.getCurLanguageIndex() == 0) {
                config.locale = Locale.getDefault();
                //上面是对应三种情况下设置三种语言设置
                //resources.updateConfiguration(config, dm);//刷新语言设置信息，这步不能少。
            } else if (mGlobalVar.getCurLanguageIndex() == 1)    // En
            {
                config.locale = Locale.ENGLISH;
                //上面是对应三种情况下设置三种语言设置
                // resources.updateConfiguration(config, dm);//刷新语言设置信息，这步不能少。
                // getBaseContext().createConfigurationContext(config);
            } else if (mGlobalVar.getCurLanguageIndex() == 2)    // En
            {
                config.locale = Locale.CHINA;
                //上面是对应三种情况下设置三种语言设置
                //resources.updateConfiguration(config, dm);//刷新语言设置信息，这步不能少。
            }
            resources.updateConfiguration(config, dm);
        }
        //floatWindowSize =  dip2px(this,30);
        floatWindowSize = (int) (((float) dip2px(this, 30) * (mGlobalVar.getFloat_Icon_Size() + 5) / 10));

        params.width = floatWindowSize;
        params.height = floatWindowSize;


        paramsFloat.width = dip2px(this, 310);
        //paramsFloat.x = panelWidth/2-paramsFloat.width/2;
        //paramsFloat.y = 0;
        paramsFloat.height = dip2px(this, 50);

        params.x = (panelWidth - paramsFloat.width) / 2 - floatWindowSize - mFloatHideSize - 1;//panelWidth/4;

        paramsHide.x = params.x + floatWindowSize + 1;
        paramsHide.width = mFloatHideSize;
        paramsHide.height = mFloatHideSize;

        paramsBtn.width = panelWidth;
        paramsBtn.height = panelHeight;

        paramsQuick.width = dip2px(this, 120);
        paramsQuick.x = panelWidth / 2 - paramsQuick.width / 2;
        paramsQuick.y = paramsFloat.height;
        paramsQuick.height = dip2px(this, 130);

        paramsPosition.y = paramsFloat.height;
        paramsPosition.width = dip2px(this, 200);
        paramsPosition.height = dip2px(this, 150);

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        floatLogoLayout = (ConstraintLayout) inflater.inflate(R.layout.float_layout, null);
        layout_float_menu = (LinearLayout) inflater.inflate(R.layout.float_menu_layout, null);
        quickViewLayout = (LinearLayout) inflater.inflate(R.layout.quickview_layout, null);
        ll_position_data = (LinearLayout) inflater.inflate(R.layout.position_data_layout, null);
        float_hide_layout = (AbsoluteLayout) inflater.inflate(R.layout.float_hide_layout, null);
        layout_btn_notouch = (AbsoluteLayout) inflater.inflate(R.layout.btn_notouch_layout, null);

        ll_float_menu_quick = (LinearLayout) layout_float_menu.findViewById(R.id.ll_float_menu_quick);
        ll_float_menu_setting = (LinearLayout) layout_float_menu.findViewById(R.id.ll_float_menu_setting);
        ll_float_menu_home = (LinearLayout) layout_float_menu.findViewById(R.id.ll_float_menu_home);
        ll_float_menu_visible = (LinearLayout) layout_float_menu.findViewById(R.id.ll_float_menu_visible);
        ll_float_menu_data = (LinearLayout) layout_float_menu.findViewById(R.id.ll_float_menu_data);
        iv_float_menu_visible = (ImageView) layout_float_menu.findViewById(R.id.iv_float_menu_visible);
        tv_float_menu_visible = (TextView) layout_float_menu.findViewById(R.id.tv_float_menu_visible);
        iv_float_menu_data = (ImageView) layout_float_menu.findViewById(R.id.iv_float_menu_data);
        iv_float_menu_quick = (ImageView) layout_float_menu.findViewById(R.id.iv_float_menu_quick);
        lv_btnlist = (ListView) quickViewLayout.findViewById(R.id.lv_quick_view);
        btn_position_data_save = (Button) ll_position_data.findViewById(R.id.btn_position_data_save);
        btn_position_data_load = (Button) ll_position_data.findViewById(R.id.btn_position_data_load);

        ll_float_menu_quick.setOnClickListener(onClickListener);
        ll_float_menu_setting.setOnClickListener(onClickListener);
        ll_float_menu_home.setOnClickListener(onClickListener);
        ll_float_menu_visible.setOnClickListener(onClickListener);
        ll_float_menu_data.setOnClickListener(onClickListener);
        btn_position_data_save.setOnClickListener(onClickListener);
        btn_position_data_load.setOnClickListener(onClickListener);

        ll_float_menu_quick.setOnTouchListener(onTouchListener);
        ll_float_menu_setting.setOnTouchListener(onTouchListener);
        ll_float_menu_home.setOnTouchListener(onTouchListener);
        ll_float_menu_visible.setOnTouchListener(onTouchListener);
        ll_float_menu_data.setOnTouchListener(onTouchListener);

        quickViewLayout.setOnTouchListener(onTouchListener);


        //bIsLogoShow111 =  true;
        windowManager.addView(floatLogoLayout, params);

        if (Transfer_Con.ENABLE_S2_QUICK_MENU || Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
            windowManager.addView(float_hide_layout, paramsHide);
            bIsMenuKeyShow = true;
        }

        windowManager.addView(layout_float_menu, paramsFloat);

        if (!(Transfer_Con.ENABLE_S2_QUICK_MENU || Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU)) {
            windowManager.addView(layout_btn_notouch, paramsBtn);
            bIsBtnNoTouchShow = true;
        }

        //Rect rect = new Rect();
        //new View(this).getWindowVisibleDisplayFrame(rect);

        //Log.d(TAG,String.format("Screen1=%d,%d,%d,%d",rect.left,rect.top,rect.right,rect.bottom));

        bIsLogoShow = true;

        bIsMenuShow = true;

        pttbl_temp = new int[mGlobalVar.getDeviceMaxButton() * 2];
        combo_pttbl_temp = new int[4][mGlobalVar.getDeviceMaxButton() * 2];


        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
        {
          System.arraycopy(mGlobalVar.coorTbl,0,pttbl_temp,0,mGlobalVar.getDeviceMaxButton() * 2);
            for (int k = 0; k < 4; k++) {
                System.arraycopy(mGlobalVar.coorTbl,mGlobalVar.getDeviceMaxButton()*(k+1)*2,combo_pttbl_temp[k],0,mGlobalVar.getDeviceMaxButton() * 2);
            }
        }
        else {
            pttbl_temp = mGlobalVar.getPTTable();
        }
        if (Transfer_Con.ENABLE_S2_MENU_COVER) {
            if (mGlobalVar.getIsForceS2Enable()) {
                S2_X = pttbl_temp[Transfer_Con.TI_BUTTON_S2 * 2 + 1];
                S2_Y = pttbl_temp[Transfer_Con.TI_BUTTON_S2 * 2];
            }
            //Log.d(TAG, String.format("x=%d,y=%d", S2_X, S2_Y));
        }

        listData = new ArrayList<Map<String, Object>>();
        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
        {
            for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                for(int a=0;a<3;a++)
                    g_u8tAttrTable[k][a]= (byte)mGlobalVar.attrTbl[k][a];
            }
        }
        else {
            for (int a = 0; a < 3; a++) {
                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, u8DataBuffer)) {
                    for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                        g_u8tAttrTable[k][a] = u8DataBuffer[16 + k];
                    }
                }
            }
        }
        for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {

            if (Transfer_Con.ENABLE_S2_QUICK_MENU && (!Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU)) {
                if (mGlobalVar.getIsSupportMenuKey()) {
                    if (k == Transfer_Con.TI_BUTTON_S2)
                        continue;
                }
            }
            if (((g_u8tAttrTable[k][0] & Transfer_Con.ATTR_MASK) != 0)&&((g_u8tAttrTable[k][0]&0xff)!=0xff)) {   // have function
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("btn", k);
                map.put("func", (int) g_u8tAttrTable[k][0]);
                if ((g_u8tAttrTable[k][0] & 0x80) == 0x80) {    // on
                    map.put("sw", true);
                } else {
                    map.put("sw", false);
                }
                //Log.d(TAG,"attr 0: "+String.format("0x%x",g_u8tAttrTable[k][0] ));
                listData.add(map);
            }
        }

        if(!Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP) {
            for (int k = 0; k < 4; k++) {
                if ((g_u8tAttrTable[Transfer_Con.TI_BUTTON_L1 + k][0] & 0xC0) == 0xC0) {
                    if (mGlobalVar.tranGetComboTbl((byte) k, (byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 0, u8DataBuffer)) {
                        int a;
                        String str = "";
                        for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                            combo_pttbl_temp[k][a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                            combo_pttbl_temp[k][a] += (int) (u8DataBuffer[2 * a] & 0xff);
                            str += String.valueOf(combo_pttbl_temp[k][a]) + ", ";
                        }
                        Log.d(TAG, str);
                        str = "";
                        if (mGlobalVar.tranGetComboTbl((byte) k, (byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 1, u8DataBuffer)) {
                            for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                combo_pttbl_temp[k][mGlobalVar.getDeviceMaxButton() + a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                combo_pttbl_temp[k][mGlobalVar.getDeviceMaxButton() + a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                // Log.d(TAG,"wwww "+String.valueOf(combo_pttbl_temp[k][mGlobalVar.getDeviceMaxButton() + a]));
                                str += String.valueOf(combo_pttbl_temp[k][a]) + ", ";
                                //Log.d(TAG,"w2 "+String.valueOf(combo_pttbl_temp[k][mGlobalVar.getDeviceMaxButton() + a]));
                            }
                            Log.d(TAG, str);
                        }
                    }
                }
            }
        }

        showFloatImage();

        myBroadcastReceive = new MyBroadcastReceive();
//注册广播接收,注意：要监听这个系统广播就必须用这种方式来注册，不能再xml中注册，否则不能生效
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction("android.intent.action.CONFIGURATION_CHANGED");
        filter.addAction("com.opd.soeghtool.content");
        filter.addAction("com.opd.soeghtool.floatview");
        registerReceiver(myBroadcastReceive, filter);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                    /*if(bIsLogoShow111)
                    {
                        params.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
                        windowManager.addView(floatLogoLayout, params);
                        bIsLogoShow111 = false;
                    }
                    else */
                if ((!bIsHalfShow) && (!bIsPositionShow)) {
                    floatLogoLayout.scrollBy(0, floatWindowSize / 2);
                    windowManager.updateViewLayout(floatLogoLayout, params);
                    bIsHalfShow = true;
                    if (bIsMenuShow) {
                        windowManager.removeView(layout_float_menu);
                        bIsMenuShow = false;
                    }
                    if (bIsQuickShow) {
                        windowManager.removeView(quickViewLayout);
                        bIsQuickShow = false;
                    }
                }
                /*
                Configuration mConfiguration = FloatMenuService.this.getResources().getConfiguration(); //获取设置的配置信息
                if(Configuration.ORIENTATION_PORTRAIT == mConfiguration.orientation)
                {
                    //hideWin();
                    Log.d(TAG,"ORIENTATION_PORTRAIT Hide Win");
                }
                else
                {
                    Log.d(TAG,"ORIENTATION_LANDSCAPE Show Win");
                }

                if(mGlobalVar.enumDevice()<=0)
                {
                    Log.d(TAG,"USB Disconnect");
                }
                else
                {
                    Log.d(TAG,"USB Connect");
                }
                */
            }
        };

        handlerLandscape = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Configuration mConfiguration = FloatMenuService.this.getResources().getConfiguration(); //获取设置的配置信息
                g_prvOrientation = mConfiguration.orientation;
                if (Configuration.ORIENTATION_PORTRAIT == mConfiguration.orientation) {
                    hideWin();
                    Log.d(TAG, "ORIENTATION_PORTRAIT Hide Win");
                }
                //orientationStatus = mConfiguration.orientation; //获取屏幕方向
                //Log.i(TAG, "orientationStatus:" + mConfiguration.orientation);
            }
        };
        if (Transfer_Con.ENABLE_OPPO_MSG_HANDLE) {
            if (android.os.Build.BRAND.equalsIgnoreCase("OPPO")) {
                handlerSystem = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);

                        Configuration mConfiguration = FloatMenuService.this.getResources().getConfiguration(); //获取设置的配置信息
                        if (g_prvOrientation != mConfiguration.orientation) {
                            g_prvOrientation = mConfiguration.orientation;
                            if (Configuration.ORIENTATION_PORTRAIT == mConfiguration.orientation) {
                                hideWin();
                                Log.d(TAG, "ORIENTATION_PORTRAIT");
                            } else {
                                showWin();
                                Log.d(TAG, "ORIENTATION_LANDSCAPE");
                            }
                        }

                        if (mGlobalVar.isUSBDeviceListEmpty()) {
                            Log.d(TAG, "USB Disconnect");
                            if (mGlobalVar.getbIsUsbConnect()) {
                                mGlobalVar.setbIsUsbConnect(false);
                                mGlobalVar.setbIsTransferMode(false);
                                mGlobalVar.myUsbDevice = null;
                                mGlobalVar.myInterface = null;
                                mGlobalVar.epOut = null;
                                mGlobalVar.epIn = null;
                                byte[] data = new byte[4];
                                data[0] = 0x10;
                                data[1] = 0;
                                udpSocketHelper.sendCmd(data, 2);
                                mGlobalVar.setIsFloatServiceRunning(false);
                                stopSelf();
                            }
                        }
                        message2 = handlerSystem.obtainMessage();
                        message2.what = 0;
                        message2.arg1 = 1;
                        message2.arg2 = 2;
                        handlerSystem.sendMessageDelayed(message2, 5000);//MENU_STAY_TIME);
                    }
                };
            }
        }
        if (mGlobalVar.getIsFloatMenuGuide()) {
            // User Guide
            if (!bIsQuickShow) {
                windowManager.addView(quickViewLayout, paramsQuick);
                //windowManager.addView(float_back_layout, paramsBack);
                bIsQuickShow = true;
            }
            Intent intent = new Intent(FloatMenuService.this, UserGuideService.class);
            startService(intent);
        } else {
            message1 = handlerLandscape.obtainMessage();
            message1.what = 0;
            message1.arg1 = (int) paramsFloat.x;
            message1.arg2 = (int) paramsFloat.y;
            handlerLandscape.sendMessageDelayed(message1, 10000);


            message = handler.obtainMessage();
            message.what = 0;
            message.arg1 = (int) paramsFloat.x;
            message.arg2 = (int) paramsFloat.y;
            handler.sendMessageDelayed(message, MENU_STAY_TIME);//MENU_STAY_TIME);
        }
        if (Transfer_Con.ENABLE_OPPO_MSG_HANDLE) {
            if (android.os.Build.BRAND.equalsIgnoreCase("OPPO")) {
                message2 = handlerSystem.obtainMessage();
                message2.what = 0;
                message2.arg1 = 1;
                message2.arg2 = 2;
                handlerSystem.sendMessageDelayed(message2, 5000);//MENU_STAY_TIME);
            }
        }
        floatLogoLayout.setOnTouchListener(new View.OnTouchListener() {
            int prev_x = 0, prev_y = 0;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        handler.removeMessages(0);
                        prev_x = (int) event.getRawX();
                        prev_y = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if ((Math.abs(prev_x - (int) event.getRawX()) > 20) || ((Math.abs(prev_y - (int) event.getRawY()) > 20))) {
                            params.x = (int) event.getRawX() - floatWindowSize / 2;
                            windowManager.updateViewLayout(floatLogoLayout, params);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (bIsHalfShow) {
                            floatLogoLayout.scrollBy(0, -floatWindowSize / 2);
                            windowManager.updateViewLayout(floatLogoLayout, params);
                            bIsHalfShow = false;
                        } else {
                            if ((Math.abs(prev_x - (int) event.getRawX()) < 50) && (Math.abs(prev_y - (int) event.getRawY()) < 50)) {
                                if (bIsQuickShow) {
                                    windowManager.removeView(quickViewLayout);
                                    bIsQuickShow = false;
                                } else if (!bIsMenuShow) {
                                    windowManager.addView(layout_float_menu, paramsFloat);
                                    bIsMenuShow = true;
                                } else {
                                    windowManager.removeView(layout_float_menu);
                                    bIsMenuShow = false;
                                }
                            }
                        }

                        if (((params.x + floatWindowSize / 2) > (panelWidth - paramsFloat.width) / 2) && ((params.x - floatWindowSize / 2) < (panelWidth + paramsFloat.width) / 2)) {
                            if ((params.x) < (panelWidth) / 2)
                                params.x = (panelWidth - paramsFloat.width) / 2 - floatWindowSize - 2;
                            else
                                params.x = (panelWidth + paramsFloat.width) / 2 + floatWindowSize;
                            windowManager.updateViewLayout(floatLogoLayout, params);
                        }
                        if (Transfer_Con.ENABLE_S2_QUICK_MENU || Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
                            if (mGlobalVar.getIsSupportMenuKey()) {
                                if ((Math.abs(prev_x - (int) event.getRawX()) > 50) || ((Math.abs(prev_y - (int) event.getRawY()) > 50))) {
                                    paramsHide.x = params.x + floatWindowSize + 1;
                                    windowManager.updateViewLayout(float_hide_layout, paramsHide);
                                    int x = (paramsHide.x + 1) * 0x7FFF / panelWidth;
                                    int y = 0x7FFF / panelHeight;
                                    mGlobalVar.menuOnPos_x = x;
                                    mGlobalVar.menuOnPos_y = y;

                                    if (Transfer_Con.ENABLE_S2_MENU_COVER) {
                                        if (mGlobalVar.getIsForceS2Enable()) {
                                            x = S2_X;
                                            y = S2_Y;
                                        }
                                    }
                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (x << 16) | y);
                                }
                            }
                        }

                        message = handler.obtainMessage();
                        message.what = 0;
                        message.arg1 = (int) paramsFloat.x;
                        message.arg2 = (int) paramsFloat.y;
                        handler.sendMessageDelayed(message, MENU_STAY_TIME);
                        break;
                }
                return false;
            }
        });

        /*
       // floatLogoLayout.setFocusableInTouchMode(true);

        floatLogoLayout.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode ==KeyEvent.KEYCODE_MENU)
                {
                    if(mGlobalVar.getIsFloatMenuGuide()) {
                        Intent stopIntent = new Intent(FloatMenuService.this, UserGuideService.class);
                        stopService(stopIntent);
                    }
                    ll_float_menu_setting.performClick();
                }
                Toast.makeText(FloatMenuService.this,"Key: "+String.valueOf(keyCode),Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        */


        if (Transfer_Con.ENABLE_S2_QUICK_MENU || Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
            float_hide_layout.setOnTouchListener(new View.OnTouchListener() {
                int flag = 0;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            if (flag == 0) {
                                flag = 1;
                            }
                            break;
                        case MotionEvent.ACTION_MOVE:

                            break;
                        case MotionEvent.ACTION_UP:
                            if (flag == 1) {

                                if (bIsBtnNoTouchShow) {
                                    if (mGlobalVar.getIsFloatMenuGuide()) {
                                        Intent stopIntent = new Intent(FloatMenuService.this, UserGuideService.class);
                                        stopService(stopIntent);
                                    }
                                    ll_float_menu_setting.performClick();
                                } else {
                                    ll_float_menu_visible.performClick();
                                }
                                flag = 0;
                            }
                            break;
                    }
                    Log.d(TAG, String.format("x:%d, y:%d", (int) event.getRawX(), (int) event.getRawY()));
                    return false;
                }
            });
        }

        if (Transfer_Con.ENABLE_S2_QUICK_MENU || Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
            if (mGlobalVar.getIsSupportMenuKey()) {
                int x = (paramsHide.x + 1) * 0x7FFF / panelWidth;
                int y = 0x7FFF / panelHeight;
                mGlobalVar.menuOnPos_x = x;
                mGlobalVar.menuOnPos_y = y;
                if (Transfer_Con.ENABLE_S2_MENU_COVER) {
                    if (mGlobalVar.getIsForceS2Enable()) {
                        x = S2_X;
                        y = S2_Y;
                    }
                }
                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (x << 16) | y);
            }
        }
        layout_float_menu.setOnTouchListener(onTouchListener);

        // Log.d(TAG,"list size="+String.valueOf(listData.size()));
        funcAdapter = new FuncAdapter(FloatMenuService.this);
        lv_btnlist.setAdapter(funcAdapter);
        lv_btnlist.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        message = handler.obtainMessage();
                        message.what = 0;
                        message.arg1 = (int) paramsFloat.x;
                        message.arg2 = (int) paramsFloat.y;
                        handler.sendMessageDelayed(message, MENU_STAY_TIME);
                        break;

                    case SCROLL_STATE_TOUCH_SCROLL:
                        handler.removeMessages(0);
                        Log.d(TAG, "List tv setOnScrollListener: ");
                        break;

                    case SCROLL_STATE_FLING:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //Toast.makeText(MainService.this,""+firstVisibleItem,Toast.LENGTH_SHORT).show();
            }
        });
        //params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        //windowManager.updateViewLayout(floatLogoLayout, params);
        //windowManager.removeView(floatLogoLayout);
        //bIsLogoShow111 =  true;
        if (Transfer_Con.ENABLE_OPPO_FOREGROUND_SERVICE) {
            if (android.os.Build.BRAND.equalsIgnoreCase("OPPO")) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    createNotificationChannel();
                }
            }
        }

    }
    private static final String CHANNEL_ID = "com.opd.soeghtool";
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        //设定的通知渠道名称
        String channelName = getString(R.string.app_name);
        //设置通知的重要程度
        int importance = NotificationManager.IMPORTANCE_LOW;
        //构建通知渠道
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);
        channel.setDescription("手易悬浮窗正在运行");
        //在创建的通知渠道上发送通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
        builder.setSmallIcon(R.drawable.round_background) //设置通知图标
                .setContentTitle("手易")//设置通知标题
                .setContentText("手易悬浮窗正在运行")//设置通知内容
                .setAutoCancel(true) //用户触摸时，自动关闭
                .setOngoing(true);//设置处于运行状态
        //向系统注册通知渠道，注册后不能改变重要性以及其他通知行为
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(channel);
        //将服务置于启动状态 NOTIFICATION_ID指的是创建的通知的ID
        startForeground(111, builder.build());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_float_menu_quick:
                    if(bIsQuickShow) {
                        iv_float_menu_quick.setImageResource(R.drawable.quick_unsel);
                        bIsQuickShow = false;
                        windowManager.removeView(quickViewLayout);
                    }
                    else
                    {
                        if(bIsPositionShow)
                        {
                            bIsPositionShow = false;
                            windowManager.removeView(ll_position_data);
                            iv_float_menu_data.setImageResource(R.drawable.import_unsel);
                        }

                        listData = new ArrayList<Map<String, Object>>();
                        for (int a = 0; a < 3; a++) {
                            if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, u8DataBuffer)) {
                                for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                    g_u8tAttrTable[k][a] = u8DataBuffer[16 + k];

                                    if(!BuildConfig.DEBUG) {
                                        if (a == 0)
                                            Log.d(TAG, String.valueOf(g_u8tAttrTable[k][a] & 0x3f));
                                    }
                                }
                            }
                        }
                        for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                            if(Transfer_Con.ENABLE_S2_QUICK_MENU&&!Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU)
                            {
                                if(mGlobalVar.getIsSupportMenuKey()) {
                                    if (k == Transfer_Con.TI_BUTTON_S2)
                                        continue;
                                }
                            }
                            if(((g_u8tAttrTable[k][0]&Transfer_Con.ATTR_MASK)!=0)&&((g_u8tAttrTable[k][0]&0xff)!=0xff)) {   // have function
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("btn",k );
                                map.put("func",(int)g_u8tAttrTable[k][0] );
                                if ((g_u8tAttrTable[k][0] & 0x80) == 0x80) {    // on
                                    map.put("sw",true );
                                } else {
                                    map.put("sw",false );
                                }
                                //Log.d(TAG,"attr 0: "+String.format("0x%x",g_u8tAttrTable[k][0] ));
                                listData.add(map);
                            }
                        }
                        funcAdapter.notifyDataSetChanged();
                        iv_float_menu_quick.setImageResource(R.drawable.quick_sel);
                        bIsQuickShow = true;
                        windowManager.addView(quickViewLayout, paramsQuick);
                    }
                    break;
                case R.id.ll_float_menu_setting:
                    if(Transfer_Con.ENABLE_OPPO_MSG_HANDLE) {
                        if (android.os.Build.BRAND.equalsIgnoreCase("OPPO")) {
                            handlerSystem.removeMessages(0);
                        }
                    }
                    hideWin();
                    Intent intent1 = new Intent(FloatMenuService.this,ButtonSettingService.class);
                    startService(intent1);
                    break;
                case R.id.ll_float_menu_home:
                    Intent intent = new Intent();
                    intent.setClass(getBaseContext(), MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getApplication().startActivity(intent);
                    //stopSelf();
                    break;
                case R.id.ll_float_menu_visible:
                    if(bIsBtnNoTouchShow)
                    {
                        bIsBtnNoTouchShow = false;
                        iv_float_menu_visible.setImageResource(R.drawable.visible);
                        tv_float_menu_visible.setText(getResources().getString(R.string.string_float_menu_visible));
                        windowManager.removeView(layout_btn_notouch);
                    }
                    else
                    {
                        bIsBtnNoTouchShow = true;
                        iv_float_menu_visible.setImageResource(R.drawable.invisible);
                        tv_float_menu_visible.setText(getResources().getString(R.string.string_float_menu_hide));
                        windowManager.addView(layout_btn_notouch,paramsBtn);
                    }
                    break;
                case R.id.ll_float_menu_data:
                    if(bIsPositionShow)
                    {
                        bIsPositionShow = false;
                        windowManager.removeView(ll_position_data);
                        iv_float_menu_data.setImageResource(R.drawable.import_unsel);
                    }
                    else
                    {
                        if(bIsQuickShow) {
                            iv_float_menu_quick.setImageResource(R.drawable.quick_sel);
                            bIsQuickShow = false;
                            windowManager.removeView(quickViewLayout);
                        }
                        windowManager.addView(ll_position_data,paramsPosition);
                        bIsPositionShow = true;
                        iv_float_menu_data.setImageResource(R.drawable.import_sel);
                    }
                    break;
                case R.id.btn_position_data_save:
                    saveCorData();
                    break;
                case R.id.btn_position_data_load:
                    AlertDialog.Builder builder = new AlertDialog.Builder(FloatMenuService.this);
                    builder.setTitle(getResources().getString(R.string.string_pop_reminder))
                            .setMessage(getResources().getString(R.string.string_pop_float_menu_load_reminder))
                            .setPositiveButton(getResources().getString(R.string.string_pop_continue), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    loadCorData();

                                }
                            })
                            .setNegativeButton(getResources().getString(R.string.string_pop_cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                    Dialog dialog = builder.create();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (Settings.canDrawOverlays(FloatMenuService.this))
                            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                    }
                    else
                    {
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    }
                    dialog.show();

                    break;
            }
        }
    };

    View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    handler.removeMessages(0);
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    message = handler.obtainMessage();
                    message.what = 0;
                    message.arg1 = (int) paramsFloat.x;
                    message.arg2 = (int) paramsFloat.y;
                    handler.sendMessageDelayed(message, MENU_STAY_TIME);
                    break;
            }
            return false;
        }
    };


    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    void showFloatImage()
    {
        int x, y;
        //ViewGroup.LayoutParams para;
        //pttbl_temp = mGlobalVar.getPTTable();
        /*
        for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++) {
            iv_btn[a].setVisibility(View.GONE);
            y = pttbl_temp[a*2] * panelHeight / 0x7FFF;
            x = pttbl_temp[a*2+1] * panelWidth / 0x7FFF;
            iv_btn[a].setX(x-mImageHalfSize);
            iv_btn[a].setY(y-mImageHalfSize);
            Log.i(TAG,"iv ; "+String.valueOf(a)+",l="+String.valueOf(y)+",t="+String.valueOf(x));
            if(Transfer_Con.ENABLE_S2_QUICK_MENU&&!Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU)
            {
                if(mGlobalVar.getIsSupportMenuKey()) {
                    if (a == Transfer_Con.TI_BUTTON_S2)
                        continue;
                }
            }
            if((pttbl_temp[a*2]!=0x7fff)||(pttbl_temp[a*2+1]!=0x7fff))
                iv_btn[a].setVisibility(View.VISIBLE);

            iv_btn[a].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG,"setOnClickListener");
                }
            });
        }*/

           TypedArray ar;
           mImageHalfSize = (int)(((float)dip2px(this,10)*(mGlobalVar.getNormal_Icon_Size() + 5) / 10));

           if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX)
               ar = getResources().obtainTypedArray(R.array.gm1_button_images);
           else
               ar = getResources().obtainTypedArray(R.array.hn1_button_images);
           int len = ar.length();
           int[] resIds = new int[len];
           for (int a = 0; a < len; a++) {
               boolean bShow = true;
               if (Transfer_Con.ENABLE_S2_QUICK_MENU && !Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
                   if (mGlobalVar.getIsSupportMenuKey()) {
                       if (a == Transfer_Con.TI_BUTTON_S2) {
                           bShow = false;
                       }
                   }
               }
               if(a == Transfer_Con.TI_BUTTON_L1) {
                   if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX) {
                       if (mGlobalVar.tranGet_Value((byte) (Transfer_Con.HID_CMD_GET_HW_SETTING), 0xFF, 0xFF, u8DataBuffer)) {
                           if ((u8DataBuffer[0] & 0x10) == 0x10)
                               bShow =  false;
                       }
                   }
               }
               if(!bIsImageAlreadyCreate)
                iv_normal_btn[a] = new ImageView(FloatMenuService.this);
               resIds[a] = ar.getResourceId(a, 0);
               iv_normal_btn[a].setImageResource(resIds[a]);


               y = pttbl_temp[a * 2] * panelHeight / 0x7FFF;
               x = pttbl_temp[a * 2 + 1] * panelWidth / 0x7FFF;
               //Log.d(TAG,String.format("wwwww x=%d, y=%d",x,y));

               iv_normal_btn[a].setX(x - mImageHalfSize);
               iv_normal_btn[a].setY(y - mImageHalfSize);
               ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(mImageHalfSize * 2, mImageHalfSize * 2);
               iv_normal_btn[a].setAlpha(((float) mGlobalVar.getNormal_Icon_Alpha()) / 10);
               if ((pttbl_temp[a * 2] == 0x7fff) && (pttbl_temp[a * 2 + 1] == 0x7fff))
                   bShow =  false;

               if(!bShow)
                   iv_normal_btn[a].setVisibility(View.GONE);
               else
                    iv_normal_btn[a].setVisibility(View.VISIBLE);
               if(!bIsImageAlreadyCreate)
               layout_btn_notouch.addView(iv_normal_btn[a], lp);

           }
           ar.recycle();
    /*
        for(int k=0;k<4;k++) {
            //combo_pttbl_temp[k]=mGlobalVar.getComboPTTable((byte)k);
            if(BuildConfig.DEBUG)
                Log.i(TAG,"iv ; "+String.valueOf(k));
            if ((g_u8tAttrTable[Transfer_Con.TI_BUTTON_L1+k][0] & 0xC0) == 0xC0) {
                for (int a = 0; a < mGlobalVar.getDeviceLeftRockerIndex(); a++) {
                    x = combo_pttbl_temp[k][a*2+1] * panelWidth / 0x7FFF;
                    y = combo_pttbl_temp[k][a*2] * panelHeight / 0x7FFF;
                    iv_combo_btn[k][a].setX(x-mImageHalfSize);
                    iv_combo_btn[k][a].setY(y-mImageHalfSize);
                    if(BuildConfig.DEBUG)
                        Log.i(TAG,"iv1 ; "+String.valueOf(a)+",l="+String.valueOf(y)+",t="+String.valueOf(x));
                    if((combo_pttbl_temp[k][a*2]!=0x7fff)||(combo_pttbl_temp[k][a*2+1]!=0x7fff))
                    iv_combo_btn[k][a].setVisibility(View.VISIBLE);
                }
            }
        }
    */
           for (int k = 0; k < 4; k++) {
               //combo_pttbl_temp[k]=mGlobalVar.getComboPTTable((byte)k);
               boolean bGroupShow = true, bIconShow = true;
               if (BuildConfig.DEBUG)
                   Log.i(TAG, "iv ; " + String.valueOf(k));
               if ((g_u8tAttrTable[Transfer_Con.TI_BUTTON_L1 + k][0] & 0xC0) != 0xC0)
                   bGroupShow = false;

               if (mGlobalVar.getDeviceIndex() == Transfer_Con.DEVICE_GM1_INDEX) {
                   if (k == 1)
                       ar = getResources().obtainTypedArray(R.array.gm1_button_combo_r1_images);
                   else if (k == 2)
                       ar = getResources().obtainTypedArray(R.array.gm1_button_combo_l2_images);
                   else if (k == 3)
                       ar = getResources().obtainTypedArray(R.array.gm1_button_combo_r2_images);
                   else //f(k==0)
                       ar = getResources().obtainTypedArray(R.array.gm1_button_combo_l1_images);
               } else {
                   if (k == 1)
                       ar = getResources().obtainTypedArray(R.array.hn1_button_combo_r1_images);
                   else if (k == 2)
                       ar = getResources().obtainTypedArray(R.array.hn1_button_combo_l2_images);
                   else if (k == 3)
                       ar = getResources().obtainTypedArray(R.array.hn1_button_combo_r2_images);
                   else //f(k==0)
                       ar = getResources().obtainTypedArray(R.array.hn1_button_combo_l1_images);
               }
               len = ar.length();
               resIds = new int[len];

               for (int a = 0; a < ar.length(); a++) {
                   if ((combo_pttbl_temp[k][a * 2] == 0x7fff) && (combo_pttbl_temp[k][a * 2 + 1] == 0x7fff))
                       bIconShow = false;
                   else
                       bIconShow = true;
                   if (a == (Transfer_Con.TI_BUTTON_L1 + k))
                       bIconShow = false;
                   x = combo_pttbl_temp[k][a * 2 + 1] * panelWidth / 0x7FFF;
                   y = combo_pttbl_temp[k][a * 2] * panelHeight / 0x7FFF;
                   if(!bIsImageAlreadyCreate)
                   iv_combo_btn[k][a] = new ImageView(FloatMenuService.this);

                   resIds[a] = ar.getResourceId(a, 0);
                   iv_combo_btn[k][a].setImageResource(resIds[a]);
                   iv_combo_btn[k][a].setX(x - mImageHalfSize);
                   iv_combo_btn[k][a].setY(y - mImageHalfSize);
                   ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(mImageHalfSize * 2, mImageHalfSize * 2);
                   iv_combo_btn[k][a].setAlpha(((float) mGlobalVar.getNormal_Icon_Alpha()) / 10);
                   if (bGroupShow && bIconShow)
                       iv_combo_btn[k][a].setVisibility(View.VISIBLE);
                   else
                       iv_combo_btn[k][a].setVisibility(View.GONE);
                   if(!bIsImageAlreadyCreate)
                   layout_btn_notouch.addView(iv_combo_btn[k][a], lp);
                   if (BuildConfig.DEBUG)
                       Log.i(TAG, "iv1 ; " + String.valueOf(a) + ",l=" + String.valueOf(y) + ",t=" + String.valueOf(x));
               }
               ar.recycle();
           }

        bIsImageAlreadyCreate =  true;
    }


    class FuncAdapter extends BaseAdapter {
        private Context context = null;

        private FuncAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int position) {
            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            FuncAdapter.ViewHolder mHolder;
            final int pos = position;
            TypedArray ar;
            if(mGlobalVar.getDeviceIndex()==Transfer_Con.DEVICE_GM1_INDEX)
                ar = getResources().obtainTypedArray(R.array.gm1_button_images);
            else
                ar = getResources().obtainTypedArray(R.array.hn1_button_images);
            int len = ar.length();
            int[] resIds = new int[len];
            if (convertView == null) {
                mHolder = new FuncAdapter.ViewHolder();
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.listview_quick_view, null, true);

                mHolder.iv_lv_btnimg = (ImageView) convertView.findViewById(R.id.iv_qv_btn);
                mHolder.sw_lv_function_onoff = (Switch) convertView.findViewById(R.id.sw_qv_btn);
                mHolder.tv_lv_function = (TextView) convertView.findViewById(R.id.tv_qv_btn);

                convertView.setTag(mHolder);
            } else {
                mHolder = (FuncAdapter.ViewHolder) convertView.getTag();
            }
            resIds[pos] = ar.getResourceId((int)listData.get(position).get("btn"), 0);
            mHolder.iv_lv_btnimg.setImageResource(resIds[pos]);
            mHolder.sw_lv_function_onoff.setChecked((boolean)listData.get(position).get("sw"));
            String strButtonFunctionName[] = getResources().getStringArray(R.array.StringButtonFunction);
            switch ((int)listData.get(position).get("func")&Transfer_Con.ATTR_MASK)
            {
                case Transfer_Con.bSkillWithDirect:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[0]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[0]);
                    break;
                case Transfer_Con.bFPSPullGunDown:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[1]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[1]);
                    break;
                case Transfer_Con.ATTR_MACRO_NEW:
                case Transfer_Con.ATTR_MACRO:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[2]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[2]);
                    break;
                case Transfer_Con.bWZRYCancelConjure:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[3]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[3]);
                    break;
                case Transfer_Con.bSwipe:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[4]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[4]);
                    break;
                case Transfer_Con.bCancelAutoEvent:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[6]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[6]);
                    break;
                case Transfer_Con.ATTR_MACRO_ADV_NEW:
                case Transfer_Con.ATTR_MACRO_ADV:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[5]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[5]);
                    break;
                case Transfer_Con.bContinueClick:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[8]);
                    break;
                case Transfer_Con.bFullRangeClick:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[9]);
                    break;
                default:
                    mHolder.tv_lv_function.setText(strButtonFunctionName[7]);
                    //mHolder.tv_lv_function.setText(Transfer_Con.tFunctionName[7]);
                    break;
            }

            mHolder.tv_lv_function.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handler.removeMessages(0);
                    message = handler.obtainMessage();
                    message.what = 0;
                    message.arg1 = (int) paramsFloat.x;
                    message.arg2 = (int) paramsFloat.y;
                    Log.d(TAG,"List tv setOnClickListener: ");
                    handler.sendMessageDelayed(message, MENU_STAY_TIME);
                }
            });

            mHolder.sw_lv_function_onoff.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handler.removeMessages(0);
                    final int index = (int)listData.get(pos).get("btn");
                    //mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_AEV_ONOFF,index,0,u8DataBuffer);
                    int data;
                    //Log.d(TAG,"data1: "+String.format("0x%x",data));
                    if(((int)g_u8tAttrTable[index][0]&0x80)==0x80)
                        data = 0;
                    else
                        data = 1;
                    //mGlobalVar.IntToByte((int)data,u8DataBuffer,0);
                    //Log.d(TAG,"data2: "+String.format("0x%x",data));
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_AEV_ONOFF,data,index);

                    for (int a = 0; a < 3; a++) {
                        if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, u8DataBuffer)) {
                            for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                g_u8tAttrTable[k][a] = u8DataBuffer[16 + k];
                            }
                        }
                    }
                    listData.clear();
                    for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                        if(Transfer_Con.ENABLE_S2_QUICK_MENU&&!Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU)
                        {
                            if(mGlobalVar.getIsSupportMenuKey()) {
                                if (k == Transfer_Con.TI_BUTTON_S2)
                                    continue;
                            }
                        }
                        if(((g_u8tAttrTable[k][0]&Transfer_Con.ATTR_MASK)!=0)&&((g_u8tAttrTable[k][0]&0xff)!=0xff)) {   // have function
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("btn",k );
                            map.put("func",(int)g_u8tAttrTable[k][0] );
                            if ((g_u8tAttrTable[k][0] & 0x80) == 0x80) {    // on
                                map.put("sw",true );
                            } else {
                                map.put("sw",false );
                            }
                            listData.add(map);
                        }
                    }
                    if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP) {
                        for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
                        {
                            for(int k=0;k<3;k++)
                            {
                                mGlobalVar.attrTbl[a][k] =g_u8tAttrTable[a][k];
                            }
                        }
                        mGlobalVar.saveGameData_GP(mGlobalVar.curPkgName, mGlobalVar.curLabelName, mGlobalVar.coorTbl, mGlobalVar.attrTbl, mGlobalVar.attrEvTbl);
                    }

                    message = handler.obtainMessage();
                    message.what = 0;
                    message.arg1 = (int) paramsFloat.x;
                    message.arg2 = (int) paramsFloat.y;
                    handler.sendMessageDelayed(message, MENU_STAY_TIME);
                }

            });

            ar.recycle();
            //Log.d(TAG,"Btn Act: "+mHolder.tv_lv_function.getText());
            return convertView;
            //mHolder.btn_lv_launch.setVisibility(View.VISIBLE);
        }


        class ViewHolder {
            private ImageView iv_lv_btnimg;
            private Switch sw_lv_function_onoff;
            private TextView tv_lv_function;
        }
    }
    @Override
    public void onDestroy()
    {
        handler.removeMessages(0);
        handlerLandscape.removeMessages(0);
        if(Transfer_Con.ENABLE_OPPO_MSG_HANDLE) {
            if (android.os.Build.BRAND.equalsIgnoreCase("OPPO")) {
                handlerSystem.removeMessages(0);
            }
        }
        unregisterReceiver(myBroadcastReceive);
        mGlobalVar.setIsFloatServiceRunning(false);
        if(bIsBtnNoTouchShow)
        {
            windowManager.removeView(layout_btn_notouch);
            bIsBtnNoTouchShow = false;
        }
        if(bIsMenuShow)
        {
            windowManager.removeView(layout_float_menu);
        }
        if(bIsQuickShow)
        {
            windowManager.removeView(quickViewLayout);
        }
        if(bIsPositionShow)
        {
            bIsPositionShow = false;
            windowManager.removeView(ll_position_data);
        }
        if(bIsLogoShow) {
            bIsLogoShow = false;
            windowManager.removeView(floatLogoLayout);
        }
        if(Transfer_Con.ENABLE_S2_QUICK_MENU||Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
            if (bIsMenuKeyShow) {
                bIsMenuKeyShow = false;
                if(BuildConfig.DEBUG)
                {
                    Log.d(TAG,"destroy hide menu");
                }
                windowManager.removeView(float_hide_layout);
            }
            if (mGlobalVar.getIsSupportMenuKey()) {
                if(Transfer_Con.ENABLE_S2_MENU_COVER)
                {
                    if(mGlobalVar.getIsForceS2Enable())
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (S2_X<<16)|S2_Y);
                    else
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 0, 0);
                }
                else {
                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 0, 0);
                }
                if(BuildConfig.DEBUG)
                {
                    Log.d(TAG,String.format("hideWin x=%d y=%d",0,0));
                }
            }
        }
        super.onDestroy();
    }

    void saveCorData()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
        {
            Toast.makeText(FloatMenuService.this, getResources().getString(R.string.string_pop_float_menu_save_fail_permitted), Toast.LENGTH_SHORT).show();
        }
        else
        {
            if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(FloatMenuService.this);
                final EditText editText = new EditText(FloatMenuService.this);
                editText.setHint(mGlobalVar.curLabelName);
                editText.setSingleLine();
                builder.setTitle(getResources().getString(R.string.string_pop_data_save_dialog_filename))
                        .setView(editText)
                        .setMessage(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String strFileName = mGlobalVar.curLabelName;

                                if (!android.text.TextUtils.isEmpty(editText.getText()))
                                    strFileName = editText.getText().toString();
                                JSONArray jsonArray = new JSONArray();
                                for (int a=0;a<mGlobalVar.coorTbl.length;a++) {
                                    jsonArray.put(mGlobalVar.coorTbl[a]);
                                }

                                for(int a=0;a<Transfer_Con.MAX_COORDINATE;a++) {

                                    for (int k=0;k<3;k++) {
                                        jsonArray.put(mGlobalVar.attrTbl[a][k]);

                                    }

                                }
                                for (int a=0;a<mGlobalVar.attrEvTbl.length;a++) {
                                    jsonArray.put(mGlobalVar.attrEvTbl[a]);
                                }
                                if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        != PackageManager.PERMISSION_GRANTED) {
                                    Toast.makeText(FloatMenuService.this, getResources().getString(R.string.string_pop_float_menu_save_fail_permitted), Toast.LENGTH_SHORT).show();
                                } else {
                                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                                        String fileName = strFileName + ".cbf";
                                        if (mGlobalVar.writeFile(fileName, jsonArray.toString())) {
                                            Toast.makeText(FloatMenuService.this, strFileName + getResources().getString(R.string.string_pop_file_save_success), Toast.LENGTH_SHORT).show();
                                        }

                                    } else {
                                        Toast.makeText(FloatMenuService.this, getResources().getString(R.string.string_pop_file_save_fail), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        });
                final AlertDialog dialog = builder.create();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Settings.canDrawOverlays(FloatMenuService.this))
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                } else {
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }
                dialog.show();
            }
            else {
                final String strDefFileName;
                if (mGlobalVar.getmCurGame() < Transfer_Con.MAX_GP_FIX_GAME_NUM)
                    strDefFileName = Transfer_Con.GameName[mGlobalVar.getmCurGame()];
                else
                    strDefFileName = mGlobalVar.getUserGameName(mGlobalVar.getmCurGame() - Transfer_Con.MAX_GP_FIX_GAME_NUM);
                AlertDialog.Builder builder = new AlertDialog.Builder(FloatMenuService.this);
                final EditText editText = new EditText(FloatMenuService.this);
                editText.setHint(strDefFileName);
                editText.setSingleLine();
                builder.setTitle(getResources().getString(R.string.string_pop_float_menu_export_data))
                        .setView(editText)
                        .setMessage(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                        .setPositiveButton(getResources().getString(R.string.string_pop_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                String strFileName = strDefFileName;

                                if (!android.text.TextUtils.isEmpty(editText.getText()))
                                    strFileName = editText.getText().toString();
                                strFileName += ".cor";
                                    if (mGlobalVar.get_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 0, u8DataBuffer)) {
                                        short a;
                                        for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                            pttbl_temp[a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                            pttbl_temp[a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                        }
                                        if (mGlobalVar.get_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 1, u8DataBuffer)) {
                                            for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                                pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                                pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                                //str+=String.valueOf(ptTbl[mGlobalVar.getDeviceMaxButton()+a])+", ";
                                            }
                                        }
                                    JSONArray jsonArray = new JSONArray();
                                    for (int data : pttbl_temp) {
                                        jsonArray.put(data);
                                    }
                                    if (mGlobalVar.writeFile(strFileName, jsonArray.toString())) {
                                        Toast.makeText(FloatMenuService.this, strFileName + getResources().getString(R.string.string_pop_file_save_success), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        });
                final AlertDialog dialog = builder.create();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Settings.canDrawOverlays(FloatMenuService.this))
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                } else {
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }
                dialog.show();
            }
        }
    }

    void loadCorData()
    {
        if (Build.VERSION.SDK_INT >= 26 && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(FloatMenuService.this, getResources().getString(R.string.string_pop_float_menu_save_fail_permitted), Toast.LENGTH_SHORT).show();
        } else {
            if (Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP) {
                ArrayList<String> fileList = mGlobalVar.getFileList("cbf");
                final String[] item = new String[fileList.size()];
                for(int a=0;a<fileList.size();a++)
                    item[a] = fileList.get(a);

                AlertDialog.Builder builder = new AlertDialog.Builder(FloatMenuService.this);
                builder.setTitle(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                        .setItems(item, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(MainActivity.this,String.valueOf(which),Toast.LENGTH_SHORT).show();
                                String fileName = item[which];
                                String content = mGlobalVar.readFile(fileName);
                                try {
                                    JSONArray jsonArray = new JSONArray(content);
                                    if(jsonArray.length()<=0)
                                        return;
                                    //String str="";
                                    for(int a=0;a<Transfer_Con.MAX_COORDINATE*2;a++)
                                    {
                                        mGlobalVar.coorTbl[a] = jsonArray.getInt(a);
                                    }
                                    //Log.d(TAG,str);
                                    // str="";
                                    for(int a=0;a<Transfer_Con.MAX_COORDINATE;a++)
                                    {

                                        for(int i=0;i<3;i++)
                                        {
                                            mGlobalVar.attrTbl[a][i] = jsonArray.getInt(Transfer_Con.MAX_COORDINATE*2+a*3+i);

                                        }

                                    }
                                    // Event table
                                    if(jsonArray.length()>=(Transfer_Con.MAX_COORDINATE*5+Transfer_Con.MAX_AUTOEVENT_LENGTH_KB))
                                    {
                                        for(int a=0;a<Transfer_Con.MAX_AUTOEVENT_LENGTH_KB;a++)    // coordinate
                                        {
                                            mGlobalVar.attrEvTbl[a] = jsonArray.getInt(Transfer_Con.MAX_COORDINATE*5+a);
                                        }
                                    }
                                    else
                                    {
                                        for(int a=0;a<Transfer_Con.MAX_AUTOEVENT_LENGTH_KB;a++)    // coordinate
                                        {
                                            mGlobalVar.attrEvTbl[a] = 0;
                                        }
                                    }

                                    // Log.d(TAG,str);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                mGlobalVar.sendCoordinateToDevice_GP(true);
                                mGlobalVar.sendAttributeToDevice_GP(true);
                                mGlobalVar.sendAttributeEventTableToDevice_GP(true);
                                mGlobalVar.saveGameData_GP(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
                                System.arraycopy(mGlobalVar.coorTbl,0,pttbl_temp,0,mGlobalVar.getDeviceMaxButton() * 2);
                                for (int k = 0; k < 4; k++) {
                                    System.arraycopy(mGlobalVar.coorTbl,mGlobalVar.getDeviceMaxButton()*(k+1)*2,combo_pttbl_temp[k],0,mGlobalVar.getDeviceMaxButton() * 2);
                                }
                                for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                    for(int a=0;a<3;a++)
                                        g_u8tAttrTable[k][a]= (byte)mGlobalVar.attrTbl[k][a];
                                }
                                showFloatImage();
                            }
                        });
                final AlertDialog dialog = builder.create();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Settings.canDrawOverlays(FloatMenuService.this))
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                } else {
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }
                dialog.show();
                //mGlobalVar.saveGameData_GP(mGlobalVar.curPkgName,mGlobalVar.curLabelName,mGlobalVar.coorTbl,mGlobalVar.attrTbl,mGlobalVar.attrEvTbl);
            } else {
                ArrayList<String> fileList = mGlobalVar.getFileList("cor");
                final String[] item = new String[fileList.size()];
                for (int a = 0; a < fileList.size(); a++)
                    item[a] = fileList.get(a);

                AlertDialog.Builder builder = new AlertDialog.Builder(FloatMenuService.this);
                builder.setTitle(getResources().getString(R.string.string_pop_data_save_dialog_input_filename))
                        .setItems(item, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Toast.makeText(MainActivity.this,String.valueOf(which),Toast.LENGTH_SHORT).show();
                                String fileName = item[which];
                                String content = mGlobalVar.readFile(fileName);

                                try {
                                    JSONArray jsonArray = new JSONArray(content);
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        pttbl_temp[i] = jsonArray.getInt(i);
                                        mGlobalVar.setPtTbl(pttbl_temp);
                                        for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                            u8DataBuffer[a * 2] = (byte) (pttbl_temp[a] & 0xff);
                                            u8DataBuffer[a * 2 + 1] = (byte) (pttbl_temp[a] >> 8);
                                        }
                                        if (mGlobalVar.set_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 0, u8DataBuffer)) {

                                            for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                                u8DataBuffer[a * 2] = (byte) (pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] & 0xff);
                                                u8DataBuffer[a * 2 + 1] = (byte) (pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] >> 8);
                                            }
                                            if (mGlobalVar.set_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 1, u8DataBuffer)) {
                                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SAVE_POINT_TBL, mGlobalVar.getmCurPhone(), mGlobalVar.getmCurGame());
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                mGlobalVar.getCurCorTbl();
                                pttbl_temp = mGlobalVar.getPTTable();
                                showFloatImage();
                            }
                        });
                final AlertDialog dialog = builder.create();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Settings.canDrawOverlays(FloatMenuService.this))
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                } else {
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }
                dialog.show();
            }
        }
    }

    public void showWin()
    {

        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getRealMetrics(dm);
        //Log.d(TAG, String.format("Show wid=%d, hei=%d", dm.widthPixels, dm.heightPixels));
        if((panelHeight!=dm.heightPixels)||(panelWidth!=dm.widthPixels)) {
            panelHeight = dm.heightPixels;
            panelWidth = dm.widthPixels;

            if (panelWidth < panelHeight) {
                int a = panelWidth;
                panelWidth = panelHeight;
                panelHeight = a;
               // Log.d(TAG, "swap to Landscape Mode");
            }
        }
        if(!bIsLogoShow) {
           // if (!mGlobalVar.getIsSettingServiceRunning())
            {
                windowManager.addView(floatLogoLayout, params);
                bIsLogoShow = true;
                if (bIsHalfShow) {
                    floatLogoLayout.scrollBy(0, -floatWindowSize/2);
                    windowManager.updateViewLayout(floatLogoLayout, params);
                    bIsHalfShow = false;
                }

                    if (!bIsBtnNoTouchShow) {

                        if(Transfer_Con.ENABLE_GAME_DATA_IN_PHONE_GP)
                        {
                            //mGlobalVar.getCoordinateFromDevice_GP();
                            //mGlobalVar.getAttributeFromDevice_GP();
                            for (int a = 0; a < 3; a++) {
                                for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                    g_u8tAttrTable[k][a] = (byte)mGlobalVar.attrTbl[k][a];
                                }
                            }
                            for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                pttbl_temp[2*k] = mGlobalVar.coorTbl[2*k];
                                pttbl_temp[2*k+1] = mGlobalVar.coorTbl[2*k+1];
                            }
                            for (int a = 0; a < 4; a++)
                            {
                                for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                    combo_pttbl_temp[a][2*k] = mGlobalVar.coorTbl[((a+1)*mGlobalVar.getDeviceMaxButton()+k)*2];
                                    combo_pttbl_temp[a][2*k+1] = mGlobalVar.coorTbl[((a+1)*mGlobalVar.getDeviceMaxButton()+k)*2+1];
                                }
                            }
                        }
                        else {
                            for (int a = 0; a < 3; a++) {
                                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, u8DataBuffer)) {
                                    for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                        g_u8tAttrTable[k][a] = u8DataBuffer[16 + k];
                                    }
                                }
                            }
                            mGlobalVar.getCurCorTbl();
                            pttbl_temp = mGlobalVar.getPTTable();
                            for (int k = 0; k < 4; k++) {
                                if ((g_u8tAttrTable[Transfer_Con.TI_BUTTON_L1 + k][0] & 0xC0) == 0xC0) {
                                    if (mGlobalVar.tranGetComboTbl((byte) k, (byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 0, u8DataBuffer)) {
                                        int a;
                                        for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                            combo_pttbl_temp[k][a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                            combo_pttbl_temp[k][a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                        }
                                        if (mGlobalVar.tranGetComboTbl((byte) k, (byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 1, u8DataBuffer)) {
                                            for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                                combo_pttbl_temp[k][mGlobalVar.getDeviceMaxButton() + a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                                combo_pttbl_temp[k][mGlobalVar.getDeviceMaxButton() + a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        showFloatImage();
                        if(!(Transfer_Con.ENABLE_S2_QUICK_MENU||Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU)) {
                            ll_float_menu_visible.performClick();
                            bIsBtnNoTouchShow = true;
                        }
                    }

                if(Transfer_Con.ENABLE_S2_QUICK_MENU||Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
                    if (!bIsMenuKeyShow) {
                        bIsMenuKeyShow = true;
                        if(BuildConfig.DEBUG)
                        {
                            Log.d(TAG,"showWin menu");
                        }
                        windowManager.addView(float_hide_layout, paramsHide);
                    }
                    if (mGlobalVar.getIsSupportMenuKey()) {
                        int x = (paramsHide.x + 1) * 0x7FFF / panelWidth;
                        int y = 0x7FFF / panelHeight;
                        mGlobalVar.menuOnPos_x = x;
                        mGlobalVar.menuOnPos_y = y;
                        if(Transfer_Con.ENABLE_S2_MENU_COVER)
                        {
                            if(mGlobalVar.getIsForceS2Enable())
                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (S2_X<<16)|S2_Y);
                            else
                                mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (x << 16) | y);
                        }
                        else
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (x << 16) | y);
                        if(BuildConfig.DEBUG)
                        {
                            Log.d(TAG,String.format("showWin x=%d y=%d",x,y));
                        }
                    }
                }
                message = handler.obtainMessage();
                message.what = 0;
                message.arg1 = (int) paramsFloat.x;
                message.arg2 = (int) paramsFloat.y;
                handler.sendMessageDelayed(message, MENU_STAY_TIME);
            }
        }
    }

    public void hideWin()
    {
        if(bIsLogoShow) {
            handler.removeMessages(0);
            windowManager.removeView(floatLogoLayout);
            bIsLogoShow = false;
            if (bIsBtnNoTouchShow) {
                windowManager.removeView(layout_btn_notouch);
                bIsBtnNoTouchShow = false;
            }
            if(bIsMenuShow) {
                windowManager.removeView(layout_float_menu);
                bIsMenuShow = false;
            }
            if(bIsQuickShow) {
                windowManager.removeView(quickViewLayout);
                bIsQuickShow = false;
            }
            if(bIsPositionShow)
            {
                bIsPositionShow = false;
                windowManager.removeView(ll_position_data);
            }
            if(Transfer_Con.ENABLE_S2_QUICK_MENU||Transfer_Con.ENABLE_GN_LOGO_QUICK_MENU) {
                if (bIsMenuKeyShow) {
                    bIsMenuKeyShow = false;
                    if(BuildConfig.DEBUG)
                    {
                        Log.d(TAG,"hideWin show menu");
                    }
                    windowManager.removeView(float_hide_layout);
                }
                if (mGlobalVar.getIsSupportMenuKey()) {
                    if(Transfer_Con.ENABLE_S2_MENU_COVER)
                    {
                        if(Transfer_Con.ENABLE_S2_MENU_COVER)
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 1, (S2_X<<16)|S2_Y);
                        else
                            mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 0, 0);
                    }
                    else
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_MENU_POS, 0, 0);
                    if(BuildConfig.DEBUG)
                    {
                        Log.d(TAG,String.format("hideWin x=%d y=%d",0,0));
                    }
                }
            }
        }
    }

    class MyBroadcastReceive extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            String action=intent.getAction();
            Log.d(TAG,"BroadcastReceiver: "+action);
            if("android.intent.action.CONFIGURATION_CHANGED".equals(action)) {
                Configuration mConfiguration = context.getResources().getConfiguration(); //获取设置的配置信息
                int ori = mConfiguration.orientation; //获取屏幕方向
                if (ori == Configuration.ORIENTATION_LANDSCAPE) {
                    //横屏
                   // Log.d(TAG, "横屏 " + String.valueOf(ori));
                    showWin();
                } else if (ori == Configuration.ORIENTATION_PORTRAIT) {
                    //竖屏
                    //Log.d(TAG, "竖屏 " + String.valueOf(ori));
                    hideWin();
                    //stopSelf();
                }
            }
            /*
            if("com.opd.soeghtool.USB_Change".equals(action))
            {
                if(mGlobalVar.enumDevice()<=0)
                {
                    Log.d(TAG,"111111111111111  USB Disconnect");
                    Toast.makeText(FloatMenuService.this,"USB Disconnect",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Log.d(TAG,"11111111111111111 USB Connect");
                    Toast.makeText(FloatMenuService.this,"USB Connect",Toast.LENGTH_SHORT).show();
                }
            }
            */
            if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {
                if(mGlobalVar.enumDevice()<1)
                {
                    mGlobalVar.setbIsUsbConnect(false);
                    mGlobalVar.setbIsTransferMode(false);
                    mGlobalVar.myUsbDevice = null;
                    mGlobalVar.myInterface = null;
                    mGlobalVar.epOut = null;
                    mGlobalVar.epIn = null;
                    byte[] data = new byte[4];
                    data[0] = 0x10;
                    data[1] = 0;
                    udpSocketHelper.sendCmd(data, 2);
                    mGlobalVar.setIsFloatServiceRunning(false);
                    stopSelf();
                }
            }

            if("com.opd.soeghtool.content".equals(action))
            {
                String name = intent.getStringExtra("Guide");
                if(name.equals("Float"))
                {
                    mGlobalVar.setIsFloatMenuGuide(false);
                    SharedPreferences.Editor editor = getSharedPreferences(Transfer_Con.SAVENAME, MODE_PRIVATE).edit();
                    editor.putBoolean("FloatMenu", mGlobalVar.getIsFloatMenuGuide());
                    editor.apply();
                    message = handler.obtainMessage();
                    message.what = 0;
                    message.arg1 = (int) paramsFloat.x;
                    message.arg2 = (int) paramsFloat.y;
                    handler.sendMessageDelayed(message, MENU_STAY_TIME);
                }
            }
            if("com.opd.soeghtool.floatview".equals(action))
            {
                String name = intent.getStringExtra("Visibility");
                if(name.equals("Show"))
                {
                    showWin();
                    if(Transfer_Con.ENABLE_OPPO_MSG_HANDLE) {
                        if (android.os.Build.BRAND.equalsIgnoreCase("OPPO")) {
                            message2 = handlerSystem.obtainMessage();
                            message2.what = 0;
                            message2.arg1 = 1;
                            message2.arg2 = 2;
                            handlerSystem.sendMessageDelayed(message2, 5000);//MENU_STAY_TIME);
                        }
                    }
                }
                else if(name.equals("Hide"))
                {
                    hideWin();
                }
            }
        }
    }

    public LocationListener locationListener = new LocationListener() {

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {

        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {

        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
            //Log.d(TAG,"1111111111111111111111111111111111111");
        }
    };
}
